import org.junit.Test;
import org.junit.internal.runners.statements.RunAfters;

/**
 * Created by andy on 2016/11/7.
 * 线程通信 wait() 和 notify()的使用
 * 子线程 10次  主线程 100次  接着 子线程 10次  主线程 100次  如此循环50次 ：
 */
public class ThreadSocket {

    final  Business business=new Business();
         @Test
         public void main(){
             new  Thread(new Runnable() {
                 public void run() {
                     for (int i=1;i<=50;i++){
                         business.sub(i);
                     }
                 }
             }).start();
             for (int i=1;i<=100;i++){
                 business.main(i);
             }
         }

    class Business {
        Boolean subFlag=true;
        public synchronized  void sub(int j){
            //现在这样通信乱
        while(!subFlag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
            for (int i=1;i<=10;i++){
                System.out.println("sub子线程 " + i + "次");
            }
            subFlag=false;
            this.notify();

        }
        public  synchronized  void main(int j){
            while (subFlag){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            for (int i=1;i<=100;i++){
                System.out.println("main主线程"+i+"次");
            }
            subFlag=true;
            this.notify();;
        }
    }
}
